// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts

import Fk

Flickable {
  id: root
  property alias skill_buttons: skill_buttons

  clip: false
  contentWidth: 117
  contentHeight: panel.height
  contentX: contentWidth - width
  width: 117
  property real maxHeight: 200
  height: Math.min(maxHeight, panel.height)
  flickableDirection: Flickable.AutoFlickIfNeeded

  ListModel {
    id: skills
  }

  Item {
    id: panel
    width: parent.width
    height: buttonFlow.height

    Flow {
      id: buttonFlow
      spacing: 0
      width: panel.width

      Repeater {
        id: skill_buttons
        model: skills
        onItemAdded: parent.forceLayout()
        SkillButton {
          skill: model.skill
          type: "active"
          enabled: false
          orig: model.orig_skill

          onPressedChanged: {
            if (isFakeSkill) {
              if (!pressed) return;
              enabled = false;
              ClientInstance.notifyServer("PushRequest", [
                "prelight", orig, (!prelighted).toString()
              ].join(","));
            } else if (enabled) {
              roomScene.activateSkill(orig, pressed, "click");
            }
          }

          // onDoubleTappedChanged: {
          //   if (doubleTapped && enabled) {
          //     roomScene.activateSkill(orig, true, "doubleClick");
          //     doubleTapped = false;
          //   }
          // }
        }
      }
    }
  }

  function addSkill(skill_name, prelight) {
    const modelContains = (m, e) => {
      for (let i = 0; i < m.count; i++) {
        if (m.get(i).orig_skill === e.orig_skill) {
          return true;
        }
      }
      return false;
    };

    const data = Lua.call("GetSkillData", skill_name);

    if (!modelContains(skills, data))
      skills.append(data);

    arrangeSkills();
  }

  function loseSkill(skill_name, prelight) {
    for (let i = 0; i < skills.count; i++) {
      const item = skills.get(i);
      if (item.orig_skill == skill_name) {
        skills.remove(i);
      }
    }

    arrangeSkills();
  }

  function clearSkills() {
    skills.clear();
  }

  function arrangeSkills() {
    let i;
    let n = skills.count;
    for (i = n - 1; i >= 0; i--) {
      const data = skills.get(i);
      if (Lua.tr(data.orig_skill).length > 3) {
        skills.move(i, n - 1, 1);
        n--;
      }
    }
    for (i = 0; i < n; i++) {
      const item = skill_buttons.itemAt(i);
      item.oddIndex = (n % 2 == 1 && i == n - 1);
    }
  }
}
